//
//  MoreView.m
//  享动
//
//  Created by darker on 16/4/8.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "MoreView.h"
#import "MoreViewTableViewCell.h"
#import "LoginViewController.h"
#import "ChangePasswordViewController.h"
#import "WebViewController.h"
#import "SDImageCache.h"
#import <UIImageView+WebCache.h>
#import "AboutUsViewController.h"

@interface MoreView ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

// 登录后的分区表头视图
@property (weak, nonatomic) IBOutlet UIView *loginHeadView;

// 登录后的分区表尾视图
@property (weak, nonatomic) IBOutlet UIView *loginFootView;

// 退出登录button
@property (weak, nonatomic) IBOutlet UIButton *exitButton;

// 分区表头视图
@property (weak, nonatomic) IBOutlet UIView *headView;

// 提示登录Label
@property (weak, nonatomic) IBOutlet UILabel *loginPrompt;

// 登录button
@property (weak, nonatomic) IBOutlet UIButton *toLogin;

// 装载用户 头像昵称的View
@property (weak, nonatomic) IBOutlet UIView *userView;

@property (nonatomic, strong) NSMutableArray *modelArray;

@end

@implementation MoreView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self = [[NSBundle mainBundle]loadNibNamed:@"more" owner:nil options:nil].firstObject;

        _tableView.frame = CGRectMake(0, 64, KWIDTH, KHEIGHT - 64);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[MoreViewTableViewCell class] forCellReuseIdentifier:@"cell"];

        BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
        
        if (isLogin == YES)
        {
            _headView.hidden = YES;
            [self request];
            // 登录后
            _loginHeadView.frame = CGRectMake(0, 0, KWIDTH, 80);
            // 装载用户 头像昵称的View
            _userView.frame = CGRectMake(0, 0, KWIDTH, 80);
            // 用户头像
            _userHearImage.frame = CGRectMake(10, 10, 60, 60);
            // 用户昵称
            _userName.frame = CGRectMake(90, 20, 200, 40);
            
            // 分区表尾
            _loginFootView.frame = CGRectMake(0, 0, KWIDTH, 50);
            // 退出登录button
            _exitButton.frame = CGRectMake(0, 0, KWIDTH, 50);
            _exitButton.layer.borderWidth = 0.1;
            _exitButton.layer.cornerRadius = 4.5;
            
            _userName.textColor = [UIColor blackColor];
            _userName.font = [UIFont systemFontOfSize:15];
            _userHearImage.backgroundColor = [UIColor grayColor];
            _userHearImage.layer.cornerRadius = 30;
            _userHearImage.clipsToBounds = YES;
            
            
            [_exitButton addTarget:self action:@selector(exitButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            
                        
            _tableView.tableHeaderView = _loginHeadView;
            _tableView.tableFooterView = _loginFootView;
            _loginHeadView.hidden = NO;
            _loginFootView.hidden = NO;
            
            
        }
        else if (isLogin == NO)
        {
            
            _headView.hidden = NO;
            _loginHeadView.hidden = YES;
            _loginFootView.hidden = YES;
            
            _headView.frame = CGRectMake(0, 0, KWIDTH, 150);
            // 立即登录button
            _toLogin.frame = CGRectMake(10, 80, KWIDTH - 20, 30);
            // 提示登录label
            _loginPrompt.frame = CGRectMake(0, 20, KWIDTH, 40);
            
            // 设置button边框粗细
            _toLogin.layer.borderWidth = 0.1;
            // 设置button圆角
            _toLogin.layer.cornerRadius = 4.5;
            _tableView.tableHeaderView = _headView;
        }
        
        
    }
    return  self;
}

- (void) request
{
    NSDictionary *parDic = @{@"_ch":@"appStore", @"_lan":@"ch", @"_nw":@"WIFI", @"_product":@"fitmix", @"_sdk":@"iPhone%20OS8.2",@"_v":@"3", @"email":[[[NSUserDefaults standardUserDefaults] objectForKey:@"name"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], @"password":[[[NSUserDefaults standardUserDefaults] objectForKey:@"password"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ,@"uid":@"0"};
    [RequestManager requestWithUrl:@"http://appt.igeekery.com/user/login.json" requestType:RequestTypePost parDic:parDic finish:^(NSData *data)
     {
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         NSDictionary *userDic = [dic objectForKey:@"user"];
         _model = [[UserModel alloc] init];
         [_model setValuesForKeysWithDictionary:userDic];
         NSLog(@"%@", _model.avatar);
         NSMutableArray *array = [NSMutableArray array];
         [array addObject:_model];
         
         dispatch_async(dispatch_get_main_queue(), ^{
             _userName.text = _model.name;
             if ([[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"] != nil)
             {
                 _userHearImage.image = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"]];
             }
             
         });
         
     }error:^(NSError *error)
     {
         NSLog(@"注册网络请求错误");
     }];

}

#pragma mark --- 点击tableViewCell 触发的方法 ---
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];

    if (indexPath.section == 0)
    {
        
        if (indexPath.row == 0)
        {
            // 点击2016全球马拉松指南 触发的方法
            WebViewController *webVc = [[WebViewController alloc] init];
            webVc.nav = self.naVc;
//            self.naVc.tabBarController.tabBar.hidden = YES;
            [self.naVc pushViewController:webVc animated:YES];
            
        }
        if (indexPath.row == 1)
        {
            // 判断是否登录
            if (isLogin == YES)
            {
                // 点击修改密码触发的方法
                ChangePasswordViewController *changeVc = [[ChangePasswordViewController alloc] init];
                
                [self.naVc pushViewController:changeVc animated:NO];
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^
               {
                   
                   UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"此操作需要登录,是否立即登录?" preferredStyle:UIAlertControllerStyleAlert];
                   
                   UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                    {
                        LoginViewController *loginVc = [[LoginViewController alloc] initWithNibName:@"login" bundle:[NSBundle mainBundle]];
                        [_naVc presentViewController:loginVc animated:YES completion:nil];
                    }];
                   UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                   [alert addAction:okAction];
                   [alert addAction:cancelAction];
                   [self.naVc presentViewController:alert animated:YES completion:nil];
                   
               });
            }
        }
    }
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否清理缓存(缓冲的图片以及资讯)" preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
            {
                // 清理缓存
                [[SDImageCache sharedImageCache]clearDisk];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:cancel];
            [alertController addAction:sure];
            [self.naVc presentViewController:alertController animated:YES completion:nil];
        }
        if (indexPath.row == 1)
        {
            AboutUsViewController *aboutVc = [[AboutUsViewController alloc] initWithNibName:@"AboutUs" bundle:[NSBundle mainBundle]];
            [self.naVc pushViewController:aboutVc animated:YES];
        }
        
    }
    


}

#pragma mark --- 返回每个分区的行数 ---
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    else if (section == 1)
    {
        return 2;
    }

    return 0;
}

#pragma mark --- 返回分区个数 ---
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

#pragma mark --- 返回tableViewCell ---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MoreViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (indexPath.section == 0)
    {
        
        if (indexPath.row == 0)
        {
            cell.label.text = @"2016全球马拉松指南";
        }
        else if (indexPath.row == 1)
        {
            cell.label.text = @"修改密码";
        }
    }
    if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            cell.label.text = @"清理缓存";
            CGFloat folderSize = 0;
            folderSize += [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
            cell.rightLabel.text = [NSString stringWithFormat:@"%.2fM", folderSize];
        }
        else if (indexPath.row == 1)
        {
            cell.label.text = @"关于我们";
        }
        
    }

    return cell;
}

#pragma mark --- 每个分区间间距 ---
- (CGFloat) tableView:( UITableView *)tableView heightForHeaderInSection:( NSInteger )section
{
    return 5.0;
}

#pragma mark --- 返回表尾与分区的间距 ---
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 5.0;
    }
    return 0;
}

#pragma mark --- 退出登录button触发方法 ---
- (void)exitButtonAction:(UIButton *)sender
{
    _headView.hidden = NO;
    _loginHeadView.hidden = YES;
    _loginFootView.hidden = YES;
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
    
    _headView.frame = CGRectMake(0, 0, KWIDTH, 150);
    // 立即登录button
    _toLogin.frame = CGRectMake(10, 80, KWIDTH - 20, 30);
    // 提示登录label
    _loginPrompt.frame = CGRectMake(0, 20, KWIDTH, 40);
    
    // 设置button边框粗细
    _toLogin.layer.borderWidth = 0.1;
    // 设置button圆角
    _toLogin.layer.cornerRadius = 4.5;
    _tableView.tableHeaderView = _headView;
}

#pragma mark --- 返回每行高度 ---
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0;
}


@end
